package com.hjm.project.settleInfo.settleInfo.utils;

import com.yxhd.encrypt.ByteUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * app和服务端对称性加密
 * @auther: wangzw
 * @date: 2018/6/11 08:39
 * @description: aes加解密工具
 */
public class AESUtil {

    private static final String CODEING="utf-8";
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 功能描述: aes加密
     * @auther: wangzw
     * @date: 2018/6/11 8:29
     */
    public static String encrypt(String data, String key) {
        try {
            key = key.substring(0, 16);
            byte[] raw = key.getBytes(CODEING);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes("utf-8"));
            return new ByteUtil().parseByte2HexStr(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 功能描述: aes解密
     * @auther: wangzw
     * @date: 2018/6/11 8:36
     */
    public static String decrypt(String data, String key) {
        try {
            key = key.substring(0, 16);
            byte[] raw = key.getBytes(CODEING);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] encrypted1 = new ByteUtil().parseHexStr2Byte(data);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, CODEING);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String str = "4D87DCDB83AC1DE36F22179BD050BB304540CBD946428167BEC74F7F78328156D4630972A902045307EA98208C83A3D22F4DB76473CF7868FB17DEE57E17822C36F5F8FEE41A16E7A55EB5E616A77E4F04A6BACBE36F6D2496891BA5695F5606";
        String key = "8889c832ebb0f90772e6036b02626411";
        System.out.println(decrypt(str,key));
    }
}
